package org.base.common.exception;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.base.common.util.MessageUtils;

@Getter
@Slf4j
public class BusinessException extends RuntimeException {

    private Integer status;

    private String message;

    public BusinessException(IExceptionInfo exceptionInfo, Object... args) {
        if (exceptionInfo == null) {
            exceptionInfo = ExceptionEnum.UNKNOWN;
        }
        this.status = exceptionInfo.getStatus();
        String msg = null;
        if (exceptionInfo instanceof ExceptionEnum) {
            final String name = ((ExceptionEnum) exceptionInfo).name();
            if (args == null || args.length == 0) {
                msg = MessageUtils.get(name);
            } else {
                msg = MessageUtils.get(name, args);
            }

        }
        if (msg == null) {
            if (args != null) {
                msg = String.format(exceptionInfo.getMsg(), args);
            } else {
                msg = exceptionInfo.getMsg();
            }
        }
        this.message = msg;
    }

    public BusinessException(Exception exception) {
        status = ExceptionEnum.UNKNOWN.getStatus();
        message = exception.getMessage();
    }

    public BusinessException(String message) {
        status = ExceptionEnum.UNKNOWN.getStatus();
        this.message = message;
    }

    public BusinessException(Integer code,String message) {
        this.status = code;
        this.message = message;
    }

    public static void throwEx(IExceptionInfo exceptionInfo) {
        throw new BusinessException(exceptionInfo);
    }

    public static void throwEx(IExceptionInfo exceptionInfo, Object data) {
        throw new BusinessException(exceptionInfo, data);
    }

}
